package com.dq.controller.api.merchant.workbench.customer;

import com.dq.exception.customException.AdminException;
import com.dq.controller.api.merchant.in.request.LevelRequest;
import com.dq.vo.Vo;
import com.dq.vo.baseVo.VO;

import com.dq.domain.org.Org;
import com.dq.domain.org.OrgCustomerLevel;
import com.dq.service.AllService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author luchangtong
 * @Date 2019/12/16 15:56
 */
@RestController
@RequestMapping("/api/merchant/workbench/customer/level")
@Api(description = "等级设置")
public class WxUserLevelController extends AllService {


    @GetMapping("level/{orgId}")
    @ApiOperation("等级列表")
    public Vo level(@PathVariable Long orgId)throws AdminException{
        Org sysDept = dao.get(Org.class,orgId);
        List<OrgCustomerLevel> levels = orgCustomerLevelRepository.findBySysDeptAndDeletedFalse(sysDept);
        return new Vo((List<OrgCustomerLevel.Vo>) VO.toVOCollection(levels));
    }

    @PostMapping("add")
    @ApiOperation("添加等级")
    public Vo add(@RequestBody LevelRequest levelRequest)throws AdminException{
        if(levelRequest.getOrgId()== null){
            throw new AdminException("请指定门店");
        }
        Org sysDept = dao.get(Org.class, levelRequest.getOrgId());
        if(sysDept == null){
            throw new AdminException("门店不存在");
        }
        OrgCustomerLevel level = new OrgCustomerLevel();
        level.setLevenName(levelRequest.getLevelName());
        level.setMaxAmount(levelRequest.getMaxAmount());
        level.setMinAmount(levelRequest.getMinAmount());
        level.setSysDept(sysDept);
        orgCustomerLevelRepository.save(level);
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("update")
    @ApiOperation("添加等级")
    public Vo update(@RequestBody LevelRequest levelRequest) throws AdminException{
        if(levelRequest.getId() == null){
            throw new AdminException("请选择等级");
        }
        OrgCustomerLevel level = dao.get(OrgCustomerLevel.class,levelRequest.getId());
        if(level == null){
            throw new AdminException("此等级不存在");
        }
        level.setLevenName(levelRequest.getLevelName());
        level.setMaxAmount(levelRequest.getMaxAmount());
        level.setMinAmount(levelRequest.getMinAmount());
        orgCustomerLevelRepository.save(level);
        return new Vo(HttpStatus.OK);
    }

    @PostMapping("delete/{id}")
    @ApiOperation("删除等级")
    public Vo delete(@PathVariable Long id) throws AdminException{
        OrgCustomerLevel level = dao.get(OrgCustomerLevel.class,id);
        if(level == null){
            throw new AdminException("等级不存在");
        }
        level.setDeleted(true);
        orgCustomerLevelRepository.save(level);
        return new Vo(HttpStatus.OK);
    }
}
